﻿
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Windows.Interop;
using MessageBox = System.Windows.MessageBox;
using CosAging.View;
using System.Diagnostics.Tracing;
using NPOI.SS.Formula.Functions;
using System.Net;
using Label = System.Windows.Controls.Label;
using System.ServiceModel.Channels;
using Binding = System.Windows.Data.Binding;
using System.Collections.Concurrent;
using NPOI.OpenXmlFormats.Dml.Diagram;
using Google.Protobuf.WellKnownTypes;
using NPOI.Util;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Data;
using Org.BouncyCastle.Utilities;
using MySqlX.XDevAPI.Common;
using System.Net.Sockets;
using static CosAging.PublicClass;
using Timer = System.Timers.Timer;
using CosAging.Class;
using System.Timers;
using System.Windows.Media.Animation;
using System.IO.Ports;

namespace CosAging
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    /// 
    public class ThisBinding : INotifyPropertyChanged

    {

        int _CursorY1_Value;
        public int CursorY1_Value
        {
            get
            {
                return _CursorY1_Value;
            }
            set
            {
                _CursorY1_Value = value;
                NotifyPropertyChanged("CursorY1_Value");
            }
        }
        int _CursorY2_Value;
        public int CursorY2_Value
        {
            get
            {
                return _CursorY2_Value;
            }
            set
            {
                _CursorY2_Value = value;
                NotifyPropertyChanged("CursorY2_Value");
            }
        }
        int _CursorY3_Value;
        public int CursorY3_Value
        {
            get
            {
                return _CursorY3_Value;
            }
            set
            {
                _CursorY3_Value = value;
                NotifyPropertyChanged("CursorY3_Value");
            }
        }
        int _CursorY4_Value;
        public int CursorY4_Value
        {
            get
            {
                return _CursorY4_Value;
            }
            set
            {
                _CursorY4_Value = value;
                NotifyPropertyChanged("CursorY4_Value");
            }
        }

        string _strCursorY1_Value;
        public string strCursorY1_Value
        {
            get
            {
                return _strCursorY1_Value;
            }
            set
            {
                _strCursorY1_Value = value;
                NotifyPropertyChanged("strCursorY1_Value");
            }
        }
        string _strCursorY2_Value;
        public string strCursorY2_Value
        {
            get
            {
                return _strCursorY2_Value;
            }
            set
            {
                _strCursorY2_Value = value;
                NotifyPropertyChanged("strCursorY2_Value");
            }
        }
        string _strCursorY3_Value;
        public string strCursorY3_Value
        {
            get
            {
                return _strCursorY3_Value;
            }
            set
            {
                _strCursorY3_Value = value;
                NotifyPropertyChanged("strCursorY3_Value");
            }
        }
        string _strCursorY4_Value;
        public string strCursorY4_Value
        {
            get
            {
                return _strCursorY4_Value;
            }
            set
            {
                _strCursorY4_Value = value;
                NotifyPropertyChanged("strCursorY4_Value");
            }
        }

        string _Illuminance1_Value;
        public string Illuminance1_Value
        {
            get
            {
                return _Illuminance1_Value;
            }
            set
            {
                _Illuminance1_Value = value;
                NotifyPropertyChanged("Illuminance1_Value");
            }
        }
        string _Illuminance2_Value;
        public string Illuminance2_Value
        {
            get
            {
                return _Illuminance2_Value;
            }
            set
            {
                _Illuminance2_Value = value;
                NotifyPropertyChanged("Illuminance2_Value");
            }
        }
        string _Illuminance3_Value;
        public string Illuminance3_Value
        {
            get
            {
                return _Illuminance3_Value;
            }
            set
            {
                _Illuminance3_Value = value;
                NotifyPropertyChanged("Illuminance3_Value");
            }
        }
        string _Illuminance4_Value;
        public string Illuminance4_Value
        {
            get
            {
                return _Illuminance4_Value;
            }
            set
            {
                _Illuminance4_Value = value;
                NotifyPropertyChanged("Illuminance4_Value");
            }
        }
        
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    public partial class CameraWindow : Window
    {
        [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
        public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);

        public UInt32[] m_nSaveImageBufSize = new UInt32[4] { 0, 0, 0, 0 };
        public IntPtr[] m_pSaveImageBuf = new IntPtr[4] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero };
        private Object[] m_BufForSaveImageLock = new Object[4];
        MyCamera.MV_FRAME_OUT_INFO_EX[] m_stFrameInfo = new MyCamera.MV_FRAME_OUT_INFO_EX[4];

        MyCamera.cbOutputExdelegate cbImage;
        MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList;
        private MyCamera[] m_pMyCamera;
        MyCamera.MV_CC_DEVICE_INFO[] m_pDeviceInfo;
        bool m_bGrabbing;
        int m_nCanOpenDeviceNum;        // ch:设备使用数量 | en:Used Device Number
        int m_nDevNum;        // ch:在线设备数量 | en:Online Device Number
        int[] m_nFrames;      // ch:帧数 | en:Frame Number
        bool m_bTimerFlag;     // ch:定时器开始计时标志位 | en:Timer Start Timing Flag Bit
        Thread m_hReceiveThread = null;
        IntPtr[] m_hDisplayHandle;
        DispatcherTimer DT =new DispatcherTimer();
        ThisBinding TB=new ThisBinding();
        //=================================================================================
        Graphics G1, G2, G3, G4;

        System.Drawing.Pen ClearPen = new System.Drawing.Pen(System.Drawing.Color.White, 1);
        System.Drawing.Pen CursorClearPen = new System.Drawing.Pen(System.Drawing.Color.Black, 2);

        System.Drawing.Pen CursorY_Pen = new System.Drawing.Pen(System.Drawing.Color.Blue, 1);

        System.Drawing.Pen GreenPen = new System.Drawing.Pen(System.Drawing.Color.Green, 1);
        System.Drawing.Pen BlackPen = new System.Drawing.Pen(System.Drawing.Color.Black, 1);
        System.Drawing.Pen SolidPen = new System.Drawing.Pen(System.Drawing.Color.Red, 1);
        System.Drawing.Pen WhitePen = new System.Drawing.Pen(System.Drawing.Color.White, 1);
        System.Drawing.Pen DashPen = new System.Drawing.Pen(System.Drawing.Color.Gray, 1);
        Bitmap MyBitMap1 = new Bitmap(800, 400); Bitmap MyBitMap2 = new Bitmap(800, 400); Bitmap MyBitMap3 = new Bitmap(800, 400); Bitmap MyBitMap4 = new Bitmap(800, 400);
        bool CursorChangeY1, CursorChangeY2, CursorChangeY3, CursorChangeY4;
        //串口实例
        SerialPort serialPort = new SerialPort();
        int Sensitivity = 5;
        public CameraWindow()
        {
            //PublicClass.计时起点();
            InitializeComponent();
            Class_Initialize();         
            this.DataContext = TB;
            //PublicClass.计时终点();
            //PublicClass.Logger.Info(PublicClass.时间差);

        }
        private void Class_Initialize()
        {
            //获取串口列表
            cbxSerialPortList.DataContext = SerialPort.GetPortNames();

            TB.strCursorY1_Value = "0"; TB.strCursorY2_Value = "0"; TB.strCursorY3_Value = "0"; TB.strCursorY4_Value = "0";
            TB.Illuminance1_Value = "0"; TB.Illuminance2_Value = "0"; TB.Illuminance3_Value = "0"; TB.Illuminance4_Value = "0";

            //PictureBox1.Image = MyBitMap1;
            //G1 = Graphics.FromImage(PictureBox1.Image);
            //G1.TranslateTransform(0, 400); //平移原点//G1.RotateTransform(-30)''''''旋转
            //G1.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系

            //PictureBox2.Image = MyBitMap2;
            //G2 = Graphics.FromImage(PictureBox2.Image);
            //G2.TranslateTransform(0, 400); //平移原点//G1.RotateTransform(-30)''''''旋转
            //G2.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系

            //PictureBox3.Image = MyBitMap3;
            //G3 = Graphics.FromImage(PictureBox3.Image);
            //G3.TranslateTransform(0, 400); //平移原点//G1.RotateTransform(-30)''''''旋转
            //G3.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系

            //PictureBox4.Image = MyBitMap4;
            //G4 = Graphics.FromImage(PictureBox4.Image);
            //G4.TranslateTransform(0, 400); //平移原点//G1.RotateTransform(-30)''''''旋转
            //G4.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系

            Read_para();

            DT.Interval = new TimeSpan(0, 0, 0, 0, 1);
            DT.Tick += cursortimer;
            DT.Start();
     
            m_pDeviceList = new MyCamera.MV_CC_DEVICE_INFO_LIST();
            m_bGrabbing = false;
            m_nCanOpenDeviceNum = 0;
            m_nDevNum = 0;
            DeviceListAcq();
            m_pMyCamera = new MyCamera[4];
            m_pDeviceInfo = new MyCamera.MV_CC_DEVICE_INFO[4];
            m_nFrames = new int[4];
            cbImage = new MyCamera.cbOutputExdelegate(ImageCallBack);
            for (int i = 0; i < 4; ++i)
            {
                m_BufForSaveImageLock[i] = new Object();
            }

            m_bTimerFlag = false;
            m_hDisplayHandle = new IntPtr[4];
        }
        public void Win_Loaded(object sender, RoutedEventArgs e)
        {

        }
        private void mainform_FormClosing(object sender, CancelEventArgs e)
        {
            bnStopGrab_Click();
            bnClose_Click();

            MainWindow.IsCameraWindowShow = false;
        }
        //============================================================================================================================================

        public void ResetMember()
        {
            m_pDeviceList = new MyCamera.MV_CC_DEVICE_INFO_LIST();
            m_bGrabbing = false;
            m_nCanOpenDeviceNum = 0;
            m_nDevNum = 0;
            DeviceListAcq();
            m_nFrames = new int[4];
            cbImage = new MyCamera.cbOutputExdelegate(ImageCallBack);
            m_bTimerFlag = false;
            m_hDisplayHandle = new IntPtr[4];
            m_pDeviceInfo = new MyCamera.MV_CC_DEVICE_INFO[4];
        }

        // ch:枚举设备 | en:Create Device List
        private void DeviceListAcq()
        {
            System.GC.Collect();
            int nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
            if (0 != nRet)
            {
                richTextBox.Text += "Enumerate devices fail!\r\n";
                return;
            }

            m_nDevNum = (int)m_pDeviceList.nDeviceNum;
            //tbDevNum.Text = m_nDevNum.ToString("d");
        }

        private void SetCtrlWhenOpen()
        {
            bnOpen.IsEnabled = false;
            bnClose.IsEnabled = true;
            bnStartGrab.IsEnabled = true;
            bnStopGrab.IsEnabled = false;
            bnContinuesMode.IsEnabled = true;
            bnContinuesMode.IsChecked = true;
            bnTriggerMode.IsEnabled = true;
            cbSoftTrigger.IsEnabled = false;
            bnTriggerExec.IsEnabled = false;

            tbExposure.IsEnabled = true;
            tbGain.IsEnabled = true;
            bnSetParam.IsEnabled = true;
        }

        // ch:初始化、打开相机 | en:Initialization and open devices
        private void bnOpen_Click()
        {
            bool bOpened = false;
            // ch:判断输入格式是否正确 | en:Determine whether the input format is correct
            try
            {
                //int.Parse(tbUseNum.Text);
            }
            catch
            {
                richTextBox.Text += "Please enter correct format!\r\n";
                return;
            }
            // ch:获取使用设备的数量 | en:Get Used Device Number
            int nCameraUsingNum = 4;// int.Parse(tbUseNum.Text);
            // ch:参数检测 | en:Parameters inspection
            if (nCameraUsingNum <= 0)
            {
                nCameraUsingNum = 1;
            }
            if (nCameraUsingNum > 4)
            {
                nCameraUsingNum = 4;
            }

            for (int i = 0, j = 0; j < m_nDevNum; j++)
            {
                //ch:获取选择的设备信息 | en:Get Selected Device Information
                MyCamera.MV_CC_DEVICE_INFO device =(MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[j], typeof(MyCamera.MV_CC_DEVICE_INFO));

                String StrTemp = "";
                if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stGigEInfo, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
                    if (gigeInfo.chSerialNumber == "00K42282963")
                    {
                        i = 3;
                    }
                    else if( gigeInfo.chSerialNumber == "00K46856150")
                    {
                        i = 0;
                    }
                    else if (gigeInfo.chSerialNumber == "00K46856161")
                    {
                        i = 2;
                    }
                    else if (gigeInfo.chSerialNumber == "00K46856056")
                    {
                        i = 1;
                    }
                    if (gigeInfo.chUserDefinedName != "")
                    {
                        StrTemp = "GEV: " + gigeInfo.chUserDefinedName + " (" + gigeInfo.chSerialNumber + ")";
                    }
                    else
                    {
                        StrTemp = "GEV: " + gigeInfo.chManufacturerName + " " + gigeInfo.chModelName + " (" + gigeInfo.chSerialNumber + ")";
                    }
                }
                else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                {
                    MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)MyCamera.ByteToStruct(device.SpecialInfo.stUsb3VInfo, typeof(MyCamera.MV_USB3_DEVICE_INFO));
                    if (usbInfo.chUserDefinedName != "")
                    {
                        StrTemp = "U3V: " + usbInfo.chUserDefinedName + " (" + usbInfo.chSerialNumber + ")";
                    }
                    else
                    {
                        StrTemp = "U3V: " + usbInfo.chManufacturerName + " " + usbInfo.chModelName + " (" + usbInfo.chSerialNumber + ")";
                    }
                }


              
                //ch:打开设备 | en:Open Device
                if (null == m_pMyCamera[i])
                {
                    m_pMyCamera[i] = new MyCamera();
                    if (null == m_pMyCamera[i])
                    {
                        return;
                    }
                }

                int nRet = m_pMyCamera[i].MV_CC_CreateDevice_NET(ref device);
                if (MyCamera.MV_OK != nRet)
                {
                    return;
                }

                nRet = m_pMyCamera[i].MV_CC_OpenDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    richTextBox.Text += String.Format("Open Device[{0}] failed! nRet=0x{1}\r\n", StrTemp, nRet.ToString("X"));
                    continue;
                }
                else
                {
                    richTextBox.Text += String.Format("Open Device[{0}] success!\r\n", StrTemp);

                    m_nCanOpenDeviceNum++;
                    m_pDeviceInfo[i] = device;
                    // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                    if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                    {
                        int nPacketSize = m_pMyCamera[i].MV_CC_GetOptimalPacketSize_NET();
                        if (nPacketSize > 0)
                        {
                            nRet = m_pMyCamera[i].MV_CC_SetIntValueEx_NET("GevSCPSPacketSize", nPacketSize);
                            if (nRet != MyCamera.MV_OK)
                            {
                                richTextBox.Text += String.Format("Set Packet Size failed! nRet=0x{0}\r\n", nRet.ToString("X"));
                            }
                        }
                        else
                        {
                            richTextBox.Text += String.Format("Get Packet Size failed! nRet=0x{0}\r\n", nPacketSize.ToString("X"));
                        }
                    }

                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerMode", (uint)MyCamera.MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_OFF);
                    m_pMyCamera[i].MV_CC_RegisterImageCallBackEx_NET(cbImage, (IntPtr)i);
                    bOpened = true;
                    if (m_nCanOpenDeviceNum == nCameraUsingNum)
                    {
                        break;
                    }
                    //i++;
                }
            }

            // ch:只要有一台设备成功打开 | en:As long as there is a device successfully opened
            if (bOpened)
            {
                //tbUseNum.Text = m_nCanOpenDeviceNum.ToString();
                SetCtrlWhenOpen();
            }
        }

        private void SetCtrlWhenClose()
        {
            bnOpen.IsEnabled = true;
            bnClose.IsEnabled = false;
            bnStartGrab.IsEnabled = false;
            bnStopGrab.IsEnabled = false;
            bnContinuesMode.IsEnabled = false;
            bnTriggerMode.IsEnabled = false;
            cbSoftTrigger.IsEnabled = false;
            bnTriggerExec.IsEnabled = false;

            bnSaveBmp.IsEnabled = false;
            tbExposure.IsEnabled = false;
            tbGain.IsEnabled = false;
            bnSetParam.IsEnabled = false;
        }

        // ch:关闭相机 | en:Close Device
        private void bnClose_Click()
        {
            for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
            {
                int nRet;

                nRet = m_pMyCamera[i].MV_CC_CloseDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    return;
                }

                nRet = m_pMyCamera[i].MV_CC_DestroyDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    return;
                }
            }

            //控件操作 ch: | en:Control Operation
            SetCtrlWhenClose();
            // ch:取流标志位清零 | en:Zero setting grabbing flag bit
            m_bGrabbing = false;
            // ch:重置成员变量 | en:Reset member variable
            ResetMember();
        }

        // ch:连续采集 | en:
        private void bnContinuesMode_CheckedChanged(object sender, EventArgs e)
        {
            if (bnContinuesMode.IsChecked==true)
            {
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerMode", (uint)MyCamera.MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_OFF);
                    cbSoftTrigger.IsEnabled = false;
                    bnTriggerExec.IsEnabled = false;
                    bnSaveBmp.IsEnabled = true;
                }
            }
        }

        // ch:打开触发模式 | en:Open Trigger Mode
        private void bnTriggerMode_CheckedChanged(object sender, EventArgs e)
        {
            if (bnTriggerMode.IsChecked == true)
            {
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerMode", (uint)MyCamera.MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON);

                    // ch:触发源选择:0 - Line0; | en:Trigger source select:0 - Line0;
                    //           1 - Line1;
                    //           2 - Line2;
                    //           3 - Line3;
                    //           4 - Counter;
                    //           7 - Software;
                    if (cbSoftTrigger.IsChecked == true)
                    {
                        m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE);
                        if (m_bGrabbing)
                        {
                            bnTriggerExec.IsEnabled = true;
                        }
                    }
                    else
                    {
                        m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_LINE0);
                    }
                    cbSoftTrigger.IsEnabled = true;
                    bnSaveBmp.IsEnabled = false;
                }
            }
        }

        private void SetCtrlWhenStartGrab()
        {
            bnStartGrab.IsEnabled = false;
            bnStopGrab.IsEnabled = true;
            bnClose.IsEnabled = false;

            if (bnTriggerMode.IsChecked == true && cbSoftTrigger.IsChecked == true)
            {
                bnTriggerExec.IsEnabled = true;
            }

            bnSaveBmp.IsEnabled = true;
        }

        // ch:取流回调函数 | en:Aquisition Callback Function
        private void ImageCallBack(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
            int nIndex = (int)pUser;

            // ch:抓取的帧数 | en:Aquired Frame Number
            ++m_nFrames[nIndex];

            lock (m_BufForSaveImageLock[nIndex])
            {
                if (m_pSaveImageBuf[nIndex] == IntPtr.Zero || pFrameInfo.nFrameLen > m_nSaveImageBufSize[nIndex])
                {
                    if (m_pSaveImageBuf[nIndex] != IntPtr.Zero)
                    {
                        Marshal.Release(m_pSaveImageBuf[nIndex]);
                        m_pSaveImageBuf[nIndex] = IntPtr.Zero;
                    }

                    m_pSaveImageBuf[nIndex] = Marshal.AllocHGlobal((Int32)pFrameInfo.nFrameLen);
                    if (m_pSaveImageBuf[nIndex] == IntPtr.Zero)
                    {
                        return;
                    }
                    m_nSaveImageBufSize[nIndex] = pFrameInfo.nFrameLen;
                }

                m_stFrameInfo[nIndex] = pFrameInfo;
                CopyMemory(m_pSaveImageBuf[nIndex], pData, pFrameInfo.nFrameLen);
            }

            MyCamera.MV_DISPLAY_FRAME_INFO stDisplayInfo = new MyCamera.MV_DISPLAY_FRAME_INFO();
            stDisplayInfo.hWnd = m_hDisplayHandle[nIndex];
            stDisplayInfo.pData = pData;
            stDisplayInfo.nDataLen = pFrameInfo.nFrameLen;
            stDisplayInfo.nWidth = pFrameInfo.nWidth;
            stDisplayInfo.nHeight = pFrameInfo.nHeight;
            stDisplayInfo.enPixelType = pFrameInfo.enPixelType;

            m_pMyCamera[nIndex].MV_CC_DisplayOneFrame_NET(ref stDisplayInfo);

            Dispatcher.Invoke(new Action(() =>
            {
                画图(nIndex);
            }));
        }

        private void bnStartGrab_Click()
        {
            int nRet;

            m_hDisplayHandle[0] = PictureBox1.Handle;
            m_hDisplayHandle[1] = PictureBox2.Handle;
            m_hDisplayHandle[2] = PictureBox3.Handle;
            m_hDisplayHandle[3] = PictureBox4.Handle;

            // ch:开始采集 | en:Start Grabbing
            for (int i = 0; i < m_nCanOpenDeviceNum; i++)
            {
                m_nFrames[i] = 0;
                m_stFrameInfo[i].nFrameLen = 0;//取流之前先清除帧长度
                m_stFrameInfo[i].enPixelType = MyCamera.MvGvspPixelType.PixelType_Gvsp_Undefined;
                nRet = m_pMyCamera[i].MV_CC_StartGrabbing_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    richTextBox.Text += String.Format("No.{0} Start Grabbing failed! nRet=0x{1}\r\n", (i + 1).ToString(), nRet.ToString("X"));
                }
            }

            //ch:开始计时  | en:Start Timing
            m_bTimerFlag = true;
            //m_hReceiveThread = new Thread(ReceiveThreadProcess);
            //m_hReceiveThread.Start();
            // ch:控件操作 | en:Control Operation
            SetCtrlWhenStartGrab();
            // ch:标志位置位true | en:Set Position Bit true
            m_bGrabbing = true;
        }

        private void cbSoftTrigger_CheckedChanged(object sender, EventArgs e)
        {
            if (cbSoftTrigger.IsChecked == true)
            {
                // ch:触发源设为软触发 | en:Set Trigger Source As Software
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE);
                }
                if (m_bGrabbing)
                {
                    bnTriggerExec.IsEnabled = true;
                }
            }
            else
            {
                bnTriggerExec.IsEnabled = false;
            }
        }

        // ch:触发命令 | en:Trigger Command
        private void bnTriggerExec_Click()
        {
            int nRet;

            for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
            {
                nRet = m_pMyCamera[i].MV_CC_SetCommandValue_NET("TriggerSoftware");
                if (MyCamera.MV_OK != nRet)
                {
                    richTextBox.Text += String.Format("No.{0} Set software trigger failed! nRet=0x{1}\r\n", (i + 1).ToString(), nRet.ToString("X"));
                }
            }        
        }

        private void SetCtrlWhenStopGrab()
        {
            bnStartGrab.IsEnabled = true;
            bnStopGrab.IsEnabled = false;
            bnClose.IsEnabled = true;

            bnTriggerExec.IsEnabled = false;
            bnSaveBmp.IsEnabled = false;
        }

        //停止采集 ch: | en:Stop Grabbing
        private void bnStopGrab_Click()
        {
            for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
            {
                m_pMyCamera[i].MV_CC_StopGrabbing_NET();
            }
            //ch:标志位设为false  | en:Set Flag Bit false
            m_bGrabbing = false;
            // ch:停止计时 | en:Stop Timing
            m_bTimerFlag = false;

            // ch:控件操作 | en:Control Operation
            SetCtrlWhenStopGrab();
        }

        // ch:点击保存图片按钮 | en:Click on Save Image Button
        private void bnSaveBmp_Click()
        {
            for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
            {
                MyCamera.MV_SAVE_IMG_TO_FILE_PARAM stSaveParam = new MyCamera.MV_SAVE_IMG_TO_FILE_PARAM();
                lock (m_BufForSaveImageLock[i])
                {
                    if (m_stFrameInfo[i].nFrameLen == 0)
                    {
                        richTextBox.Text += String.Format("No.{0} save image failed! No data!\r\n", (i + 1).ToString());
                        continue;
                    }
                    stSaveParam.enImageType = MyCamera.MV_SAVE_IAMGE_TYPE.MV_Image_Bmp;
                    stSaveParam.enPixelType = m_stFrameInfo[i].enPixelType;
                    stSaveParam.pData = m_pSaveImageBuf[i];
                    stSaveParam.nDataLen = m_stFrameInfo[i].nFrameLen;
                    stSaveParam.nHeight = m_stFrameInfo[i].nHeight;
                    stSaveParam.nWidth = m_stFrameInfo[i].nWidth;
                    stSaveParam.pImagePath = "bmp\\" +  "Dev" + i.ToString() + "_Image_w" + stSaveParam.nWidth.ToString() + "_h" + stSaveParam.nHeight.ToString() + "_fn" + m_stFrameInfo[i].nFrameNum.ToString() + ".bmp";
                    //stSaveParam.nQuality = 80;//存Jpeg时有效
                    int nRet = m_pMyCamera[i].MV_CC_SaveImageToFile_NET(ref stSaveParam);
                    if (MyCamera.MV_OK != nRet)
                    {
                        richTextBox.Text += String.Format("No.{0} save image failed! nRet=0x{1}\r\n", (i + 1).ToString(), nRet.ToString("X"));
                    }
                    else
                    {
                        richTextBox.Text += String.Format("No.{0} save image Succeed!\r\n", (i + 1).ToString());
                    }
                }
            }
        }

        // ch:设置曝光时间和增益 | en:Set Exposure Time and Gain
        private void bnSetParam_Click()
        {
            try
            {
                float.Parse(tbExposure.Text);
                float.Parse(tbGain.Text);
            }
            catch
            {
                richTextBox.Text += String.Format("Please Enter Correct Type.\r\n");
                return;
            }
            if (float.Parse(tbExposure.Text) < 0 || float.Parse(tbGain.Text) < 0)
            {
                richTextBox.Text += String.Format("Set ExposureTime or Gain fail,Because ExposureTime or Gain less than zero.\r\n");
                return;
            }

            int nRet;
            for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
            {
                bool bSuccess = true;
                m_pMyCamera[i].MV_CC_SetEnumValue_NET("ExposureAuto", 0);

                nRet = m_pMyCamera[i].MV_CC_SetFloatValue_NET("ExposureTime", float.Parse(tbExposure.Text));
                if (nRet != MyCamera.MV_OK)
                {
                    richTextBox.Text += String.Format("No.{0} Set Exposure Time Failed! nRet=0x{1}\r\n", (i + 1).ToString(), nRet.ToString("X"));
                    bSuccess = false;
                }

                m_pMyCamera[i].MV_CC_SetEnumValue_NET("GainAuto", 0);
                nRet = m_pMyCamera[i].MV_CC_SetFloatValue_NET("Gain", float.Parse(tbGain.Text));
                if (nRet != MyCamera.MV_OK)
                {
                    richTextBox.Text += String.Format("No.{0} Set Gain Failed! nRet=0x{1}\r\n", (i + 1).ToString(), nRet.ToString("X"));
                    bSuccess = false;
                }

                if (bSuccess)
                {
                    richTextBox.Text += String.Format("No.{0} Set Parameters Succeed!\r\n", (i + 1).ToString());
                }
            }
        }

        // ch:获取丢帧数 | en:Get Throw Frame Number
        private string GetLostFrame(int nIndex)
        {
            MyCamera.MV_ALL_MATCH_INFO pstInfo = new MyCamera.MV_ALL_MATCH_INFO();
            if (m_pDeviceInfo[nIndex].nTLayerType == MyCamera.MV_GIGE_DEVICE)
            {
                MyCamera.MV_MATCH_INFO_NET_DETECT MV_NetInfo = new MyCamera.MV_MATCH_INFO_NET_DETECT();
                pstInfo.nInfoSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyCamera.MV_MATCH_INFO_NET_DETECT));
                pstInfo.nType = MyCamera.MV_MATCH_TYPE_NET_DETECT;
                int size = Marshal.SizeOf(MV_NetInfo);
                pstInfo.pInfo = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(MV_NetInfo, pstInfo.pInfo, false);

                m_pMyCamera[nIndex].MV_CC_GetAllMatchInfo_NET(ref pstInfo);
                MV_NetInfo = (MyCamera.MV_MATCH_INFO_NET_DETECT)Marshal.PtrToStructure(pstInfo.pInfo, typeof(MyCamera.MV_MATCH_INFO_NET_DETECT));

                string sTemp = MV_NetInfo.nLostFrameCount.ToString();
                Marshal.FreeHGlobal(pstInfo.pInfo);
                return sTemp;
            }
            else if (m_pDeviceInfo[nIndex].nTLayerType == MyCamera.MV_USB_DEVICE)
            {
                MyCamera.MV_MATCH_INFO_USB_DETECT MV_NetInfo = new MyCamera.MV_MATCH_INFO_USB_DETECT();
                pstInfo.nInfoSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyCamera.MV_MATCH_INFO_USB_DETECT));
                pstInfo.nType = MyCamera.MV_MATCH_TYPE_USB_DETECT;
                int size = Marshal.SizeOf(MV_NetInfo);
                pstInfo.pInfo = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(MV_NetInfo, pstInfo.pInfo, false);

                m_pMyCamera[nIndex].MV_CC_GetAllMatchInfo_NET(ref pstInfo);
                MV_NetInfo = (MyCamera.MV_MATCH_INFO_USB_DETECT)Marshal.PtrToStructure(pstInfo.pInfo, typeof(MyCamera.MV_MATCH_INFO_USB_DETECT));

                string sTemp = MV_NetInfo.nErrorFrameCount.ToString();
                Marshal.FreeHGlobal(pstInfo.pInfo);
                return sTemp;
            }
            else
            {
                return "0";
            }
        }

        // ch:定时器,1秒运行一次 | en:Timer, run once a second
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (m_bTimerFlag)
            {
                //if (m_nCanOpenDeviceNum > 0)
                //{
                //    tbGrabFrame1.Text = m_nFrames[0].ToString();
                //    tbLostFrame1.Text = GetLostFrame(0);
                //}
                //if (m_nCanOpenDeviceNum > 1)
                //{
                //    tbGrabFrame2.Text = m_nFrames[1].ToString();
                //    tbLostFrame2.Text = GetLostFrame(1);
                //}
                //if (m_nCanOpenDeviceNum > 2)
                //{
                //    tbGrabFrame3.Text = m_nFrames[2].ToString();
                //    tbLostFrame3.Text = GetLostFrame(2);
                //}
                //if (m_nCanOpenDeviceNum > 3)
                //{
                //    tbGrabFrame4.Text = m_nFrames[3].ToString();
                //    tbLostFrame4.Text = GetLostFrame(3);
                //}
            }
        }

        private void MultipleDemo_FormClosing(object sender, FormClosingEventArgs e)
        {
            bnClose_Click();
        }

        private void richTextBox_DoubleClick(object sender, EventArgs e)
        {
            richTextBox.Clear();
        }

        private void richTextBox_TextChanged(object sender, EventArgs e)
        {
            richTextBox.SelectionStart = richTextBox.Text.Length;
            //richTextBox.ScrollToCaret();
        }
        //============================================================================================================================================
        private void MainWindows_Keydown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //PublicClass.KeyboardandShutdown(sender, e);
        }

        private void WINState_MouseDown(Object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }
   
        #region "禁止粘贴和右键"
        private void CommandBinding_CanExecute(Object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = false;
            e.Handled = true;
        }
        #endregion
        //打开控制面板更新参数


        private void bnStopGrab_Click(object sender, RoutedEventArgs e)
        {
            bnStopGrab_Click();
        }

        private void bnStartGrab_Click(object sender, RoutedEventArgs e)
        {
            bnStartGrab_Click();
        }

        private void bnOpen_Click(object sender, RoutedEventArgs e)
        {
            bnOpen_Click();
        }

        private void bnClose_Click(object sender, RoutedEventArgs e)
        {
            bnClose_Click();
        }

        private void bnTriggerMode_Checked(object sender, RoutedEventArgs e)
        {
            if (bnTriggerMode.IsChecked == true)
            {
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerMode", (uint)MyCamera.MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_ON);

                    // ch:触发源选择:0 - Line0; | en:Trigger source select:0 - Line0;
                    //           1 - Line1;
                    //           2 - Line2;
                    //           3 - Line3;
                    //           4 - Counter;
                    //           7 - Software;
                    if (cbSoftTrigger.IsChecked == true)
                    {
                        m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE);
                        if (m_bGrabbing)
                        {
                            bnTriggerExec.IsEnabled = true;
                        }
                    }
                    else
                    {
                        m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_LINE0);
                    }
                    cbSoftTrigger.IsEnabled = true;
                    bnSaveBmp.IsEnabled = false;
                }
                //====================去掉软除法选项，直接默认就是软触发
                cbSoftTrigger.IsChecked = true;
            }
        }

        private void PictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseMove(e, "PictureBox1", G1);
        }
        private void PictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseDown(e, "PictureBox1");
        }
        private void PictureBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseUp();
        }

        private void PictureBox2_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseMove(e, "PictureBox2", G2);
        }
        private void PictureBox2_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseDown(e, "PictureBox2");
        }
        private void PictureBox2_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseUp();
        }

        private void PictureBox3_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseMove(e, "PictureBox3", G3);
        }
        private void PictureBox3_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseDown(e, "PictureBox3");
        }
        private void PictureBox3_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseUp();
        }

        private void PictureBox4_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseMove(e, "PictureBox4", G4);
        }
        private void PictureBox4_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseDown(e, "PictureBox4");
        }
        private void PictureBox4_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox_MouseUp();
        }

        private void bnContinuesMode_Checked(object sender, RoutedEventArgs e)
        {
            if (bnContinuesMode.IsChecked == true)
            {
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerMode", (uint)MyCamera.MV_CAM_TRIGGER_MODE.MV_TRIGGER_MODE_OFF);
                    cbSoftTrigger.IsEnabled = false;
                    bnTriggerExec.IsEnabled = false;
                    bnSaveBmp.IsEnabled = true;
                }
            }

        }

        private void bnTriggerExec_Click(object sender, RoutedEventArgs e)
        {
            bnTriggerExec_Click();
        }

        private void bnSetParam_Click(object sender, RoutedEventArgs e)
        {
            bnSetParam_Click();
        }

        private void Write_para(object sender, RoutedEventArgs e)
        {
            Write_para();
        }
        private void Write_para()
        {
            myIniFile.WriteString("CameraWindow", "CursorY1_Value", TB.strCursorY1_Value);
            myIniFile.WriteString("CameraWindow", "CursorY2_Value", TB.strCursorY2_Value);
            myIniFile.WriteString("CameraWindow", "CursorY3_Value", TB.strCursorY3_Value);
            myIniFile.WriteString("CameraWindow", "CursorY4_Value", TB.strCursorY4_Value);
            myIniFile.WriteString("CameraWindow", "Exposure", tbExposure.Text);
            myIniFile.WriteString("CameraWindow", "Gain", tbGain.Text);
        }
        private void Read_para(object sender, RoutedEventArgs e)
        {
            Read_para();
        }
        private void Read_para()
        {
            //G1.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY1_Value), 800, Convert.ToInt32(TB.strCursorY1_Value));
            //G2.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY2_Value), 800, Convert.ToInt32(TB.strCursorY2_Value));
            //G3.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY3_Value), 800, Convert.ToInt32(TB.strCursorY3_Value));
            //G4.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY4_Value), 800, Convert.ToInt32(TB.strCursorY4_Value));
            TB.strCursorY1_Value = myIniFile.ReadString("CameraWindow", "CursorY1_Value", 99);
            TB.strCursorY2_Value = myIniFile.ReadString("CameraWindow", "CursorY2_Value", 99);
            TB.strCursorY3_Value = myIniFile.ReadString("CameraWindow", "CursorY3_Value", 99);
            TB.strCursorY4_Value = myIniFile.ReadString("CameraWindow", "CursorY4_Value", 99);
            TB.Illuminance1_Value = myIniFile.ReadString("CameraWindow", "Illuminance1_Value", 99);
            TB.Illuminance2_Value = myIniFile.ReadString("CameraWindow", "Illuminance2_Value", 99);
            TB.Illuminance3_Value = myIniFile.ReadString("CameraWindow", "Illuminance3_Value", 99);
            TB.Illuminance4_Value = myIniFile.ReadString("CameraWindow", "Illuminance4_Value", 99);

            tbExposure.Text = Convert.ToString(myIniFile.ReadString("CameraWindow", "Exposure", 99));
            tbGain.Text = Convert.ToString(myIniFile.ReadString("CameraWindow", "Gain", 99));

        }

        private void RepeatButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.Primitives.RepeatButton RepeatButton = (System.Windows.Controls.Primitives.RepeatButton)sender;
            string header = RepeatButton.Name;
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("_"); //匹配字符串
            string LabelName = Mid(header, 1, regex.Match(header).Index);

            string Action = Mid(header, regex.Match(header).Index + 2, header.Length - regex.Match(header).Index - 1);

            Label wantedNode = (Label)GD.FindName(LabelName);
            if (wantedNode is Label)
            {
                //'Following executed if Text element was found.
                //'Dim wantedChild As TextBlock = TryCast(wantedNode, TextBlock)
                //'wantedChild.Foreground = Brushes.Blue
                if(LabelName.Length==8)
                {
                    if (m_bGrabbing)
                    {
                        if (Action == "Down") //Yslider 向下为正
                        {
                            if (wantedNode.Content.ToString() == "0")
                            {
                                wantedNode.Content = "0";
                            }
                            else
                            {
                                wantedNode.Content = Convert.ToInt32(wantedNode.Content) - 1;
                            }

                        }
                        else
                        {
                            if (wantedNode.Content.ToString() == "400")
                            {
                                wantedNode.Content = "400";
                            }
                            else
                            {
                                wantedNode.Content = Convert.ToInt32(wantedNode.Content) + 1;
                            }
                        }
                    }

                }
                else//灯光亮度
                {
                    if (Action == "Down") //Yslider 向下为正
                    {
                        if (wantedNode.Content.ToString() == "0")
                        {
                            wantedNode.Content = "0";
                        }
                        else
                        {
                            wantedNode.Content = Convert.ToInt32(wantedNode.Content) - 1;
                        }
                    }
                    else
                    {
                        if (wantedNode.Content.ToString() == "255")
                        {
                            wantedNode.Content = "255";
                        }
                        else
                        {
                            wantedNode.Content = Convert.ToInt32(wantedNode.Content) + 1;
                        }
                    }
                    int A = Convert.ToInt32(TB.Illuminance1_Value);
                    int B = Convert.ToInt32(TB.Illuminance2_Value);
                    int C = Convert.ToInt32(TB.Illuminance3_Value);
                    int D = Convert.ToInt32(TB.Illuminance4_Value);
               
                    string str = "SA"+ String.Format("{0:D4}", A)   + "#"+ "SB" + String.Format("{0:D4}", B) + "#" + "SC" + String.Format("{0:D4}",C) + "#" + "SD" + String.Format("{0:D4}",D) + "#";
                    if (serialPort.IsOpen)
                    {
                        serialPort.Write(str);
                    }
                    else
                    {
                        MessageBox.Show("串口未打开！");
                    }
                }
            }
        }
        private void cbSoftTrigger_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)cbSoftTrigger.IsChecked)
            {
                // ch:触发源设为软触发 | en:Set Trigger Source As Software
                for (int i = 0; i < m_nCanOpenDeviceNum; ++i)
                {
                    m_pMyCamera[i].MV_CC_SetEnumValue_NET("TriggerSource", (uint)MyCamera.MV_CAM_TRIGGER_SOURCE.MV_TRIGGER_SOURCE_SOFTWARE);
                }
                if (m_bGrabbing)
                {
                    bnTriggerExec.IsEnabled = true;
                }
            }
            else
            {
                bnTriggerExec.IsEnabled = false;
            }
        }

        private void bnSaveBmp_Click(object sender, RoutedEventArgs e)
        {
            bnSaveBmp_Click();
        }
        private void PreviewTextInput_vb2(Object sender, TextCompositionEventArgs e)
        {
            System.Windows.Controls.TextBox CTextBox = (System.Windows.Controls.TextBox)sender;
            PublicClass.tb_PreviewTextInput2(CTextBox, e);
        }

        private void TextLostFocus(object sender, EventArgs e)
        {
            System.Windows.Controls.TextBox TextBox_Text = (System.Windows.Controls.TextBox)sender;
        }

        #region "游标开始拖动"
        private void PictureBox_MouseDown(System.Windows.Forms.MouseEventArgs e, string PB)
        {
            if (m_bGrabbing)
            {
                int TempY, TempX;
                TempX = e.X;
                TempY = 400 - e.Y;

                if (PB == "PictureBox1" & (Math.Abs(Convert.ToInt32(TB.strCursorY1_Value) - TempY) < Sensitivity))
                {
                    CursorChangeY1 = true;
                    return;
                }
                if (PB == "PictureBox2" & (Math.Abs(Convert.ToInt32(TB.strCursorY2_Value) - TempY) < Sensitivity))
                {
                    CursorChangeY2 = true;
                    return;
                }
                if (PB == "PictureBox3" & (Math.Abs(Convert.ToInt32(TB.strCursorY3_Value) - TempY) < Sensitivity))
                {
                    CursorChangeY3 = true;
                    return;
                }
                if (PB == "PictureBox4" & (Math.Abs(Convert.ToInt32(TB.strCursorY4_Value) - TempY) < Sensitivity))
                {
                    CursorChangeY4 = true;
                    return;
                }

            }        
        }


        #endregion
        #region "拖动游标"
        private void PictureBox_MouseMove(System.Windows.Forms.MouseEventArgs e,string PB,Graphics GH)
        {

                int TempY, TempX;
                TempX = e.X;
                TempY = 400 - e.Y;

                if (CursorChangeY1 == true)
                {
                    if (TempY < 400 & TempY > 0)
                    {
                        //G1.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY1_Value), 800, Convert.ToInt32(TB.strCursorY1_Value));
                    TB.strCursorY1_Value = TempY.ToString();
                    }
                    else if (TempY >= 400)
                    {
                        //G1.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY1_Value), 800, Convert.ToInt32(TB.strCursorY1_Value));
                    TB.strCursorY1_Value = "400";
                    }
                    else if (TempY <= 0)
                    {
                        //G1.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY1_Value), 800, Convert.ToInt32(TB.strCursorY1_Value));
                    TB.strCursorY1_Value = "0";
                    }
                }
            if (CursorChangeY2 == true)
            {
                if (TempY < 400 & TempY > 0)
                {
                    //G2.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY2_Value), 800, Convert.ToInt32(TB.strCursorY2_Value));
                    TB.strCursorY2_Value = TempY.ToString();
                }
                else if (TempY >= 400)
                {
                    //G2.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY2_Value), 800, Convert.ToInt32(TB.strCursorY2_Value));
                    TB.strCursorY2_Value = "400";
                }
                else if (TempY <= 0)
                {
                    //G2.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY2_Value), 800, Convert.ToInt32(TB.strCursorY2_Value));
                    TB.strCursorY2_Value = "0";
                }
            }
            if (CursorChangeY3 == true)
            {
                if (TempY < 400 & TempY > 0)
                {
                    //G3.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY3_Value), 800, Convert.ToInt32(TB.strCursorY3_Value));
                    TB.strCursorY3_Value = TempY.ToString();
                }
                else if (TempY >= 400)
                {
                    //G3.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY3_Value), 800, Convert.ToInt32(TB.strCursorY3_Value));
                    TB.strCursorY3_Value = "400";
                }
                else if (TempY <= 0)
                {
                    //G3.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY3_Value), 800, Convert.ToInt32(TB.strCursorY3_Value));
                    TB.strCursorY3_Value = "0";
                }
            }
            if (CursorChangeY4 == true)
            {
                if (TempY < 400 & TempY > 0)
                {
                    //G4.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY4_Value), 800, Convert.ToInt32(TB.strCursorY4_Value));
                    TB.strCursorY4_Value = TempY.ToString();
                }
                else if (TempY >= 400)
                {
                    //G4.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY4_Value), 800, Convert.ToInt32(TB.strCursorY4_Value));
                    TB.strCursorY4_Value = "400";
                }
                else if (TempY <= 0)
                {
                    //G4.DrawLine(CursorClearPen, 0, Convert.ToInt32(TB.strCursorY4_Value), 800, Convert.ToInt32(TB.strCursorY4_Value));
                    TB.strCursorY4_Value = "0";
                }
            }
            //CursorPaint(PB);

        }

        private void cursortimer(object sender, EventArgs e)
        {
            //ShowGrid();

            //G1.DrawLine(CursorY1_Pen, 0, Convert.ToInt32(TB.strCursorY1_Value), 800, Convert.ToInt32(TB.strCursorY1_Value));

            //G2.DrawLine(CursorY2_Pen, 0, Convert.ToInt32(TB.strCursorY2_Value), 800, Convert.ToInt32(TB.strCursorY2_Value));

            //G3.DrawLine(CursorY3_Pen, 0, Convert.ToInt32(TB.strCursorY3_Value), 800, Convert.ToInt32(TB.strCursorY3_Value));

            //G4.DrawLine(CursorY4_Pen, 0, Convert.ToInt32(TB.strCursorY4_Value), 800, Convert.ToInt32(TB.strCursorY4_Value));
            //PictureBox1.Refresh();
            //PictureBox2.Refresh();
            //PictureBox3.Refresh();
            //PictureBox4.Refresh();
        }

        #endregion
        #region "结束游标拖动"
        private void PictureBox_MouseUp()
        {
 
            CursorChangeY1 = false; CursorChangeY2 = false; CursorChangeY3 = false; CursorChangeY4 = false;
        }

        #endregion
        public void ReceiveThreadProcess()
        {
            MyCamera.MV_FRAME_OUT stFrameInfo = new MyCamera.MV_FRAME_OUT();
            MyCamera.MV_DISPLAY_FRAME_INFO stDisplayInfo = new MyCamera.MV_DISPLAY_FRAME_INFO();
            int nRet = MyCamera.MV_OK;

            while (m_bGrabbing)
            {
                for(int i=0;i<4;i++)
                {
                    nRet = m_pMyCamera[i].MV_CC_GetImageBuffer_NET(ref stFrameInfo, 5000);
                
                           
                    if (nRet == MyCamera.MV_OK)
                    {
                        IntPtr hWnd = IntPtr.Zero;
                        Dispatcher.Invoke(new Action(() =>
                        {
                            if (i == 0) { hWnd = PictureBox1.Handle; }
                            else if (i == 1) { hWnd = PictureBox2.Handle; }
                            else if (i == 2) { hWnd = PictureBox3.Handle; }
                            else if (i == 3) { hWnd = PictureBox4.Handle; }
                        }));

                        stDisplayInfo.hWnd = hWnd;
                        stDisplayInfo.pData = stFrameInfo.pBufAddr;
                        stDisplayInfo.nDataLen = stFrameInfo.stFrameInfo.nFrameLen;
                        stDisplayInfo.nWidth = stFrameInfo.stFrameInfo.nWidth;
                        stDisplayInfo.nHeight = stFrameInfo.stFrameInfo.nHeight;
                        stDisplayInfo.enPixelType = stFrameInfo.stFrameInfo.enPixelType;

                        m_pMyCamera[i].MV_CC_DisplayOneFrame_NET(ref stDisplayInfo);
                        m_pMyCamera[i].MV_CC_FreeImageBuffer_NET(ref stFrameInfo);



                        Dispatcher.Invoke(new Action(() =>
                        {
                            画图(i);
                        }));
                    }
                }
            }
        }
        private void 画图(int Index)
        {
            int Y=0; Graphics G1;
            if (Index == 0) 
            {
                Y = Convert.ToInt32(TB.strCursorY1_Value);
                G1 = PictureBox1.CreateGraphics();
                G1.TranslateTransform(0, PictureBox1.Height); //平移原点//G1.RotateTransform(-30)''''''旋转
                G1.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系
            }
            else if (Index == 1) 
            { 
                Y = Convert.ToInt32(TB.strCursorY2_Value);
                G1 = PictureBox2.CreateGraphics();
                G1.TranslateTransform(0, PictureBox2.Height); //平移原点//G1.RotateTransform(-30)''''''旋转
                G1.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系
            }
            else if (Index == 2) 
            { 
                Y = Convert.ToInt32(TB.strCursorY3_Value);
                G1 = PictureBox3.CreateGraphics();
                G1.TranslateTransform(0, PictureBox3.Height); //平移原点//G1.RotateTransform(-30)''''''旋转
                G1.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系
            }
            else
            { 
                Y = Convert.ToInt32(TB.strCursorY4_Value);
                G1 = PictureBox4.CreateGraphics();
                G1.TranslateTransform(0, PictureBox4.Height); //平移原点//G1.RotateTransform(-30)''''''旋转
                G1.ScaleTransform(1.0F, -1.0F); //比例缩放,为了将默认坐标系转换成常用坐标系
            }


            //十字线
            G1.DrawLine(SolidPen, 0, 200, 800, 200);
            G1.DrawLine(SolidPen, 400, 0, 400, 400);
            //
            G1.DrawLine(CursorY_Pen, 0,Y,800,Y);
            G1.Dispose();
        }
        /// <summary>
        /// 打开或关闭串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSwitch_Click(object sender, RoutedEventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                //设定参数
                serialPort.PortName = "COM9"; //cbxSerialPortList.SelectedItem.ToString();
                serialPort.BaudRate = 19200;
                serialPort.Parity = Parity.None;
                serialPort.DataBits = 8;
                serialPort.StopBits = StopBits.One;

                try
                {
                    //打开串口
                    serialPort.Open();
                    MessageBox.Show("灯控串口打开成功");
                    打开关闭串口.Content = "关闭串口";
                }
                catch (Exception)
                {
                    MessageBox.Show("无法打开灯控串口，请检查是否被占用");
                    this.Close();
                    return;
                }
            }
            else
            {
                if (serialPort != null)
                {
                    //关闭串口
                    serialPort.Close();
                    MessageBox.Show("灯控串口关闭成功");
                    打开关闭串口.Content = "打开串口";
                }
            }           
        }
        public static string Mid(string param, int startIndex, int length)
        {
            string result = param.Substring(startIndex - 1, length);
            return result;
        }
        public static string Mid(string param, int startIndex)
        {
            string result = param.Substring(startIndex - 1);
            return result;
        }
    }
}
